import axios from 'axios'

const instance: any = axios.create({
  timeout: 5000
})

/**
 * 封装 http 请求的方法
 * @param option 配置对象，属性包括
 * method 请求方法
 * path 请求接口地址
 * params 请求参数
 */
async function http(option: any = {}) {
  let result: any = null
  const method = option.method.toLowerCase()
  switch (method) {
    case 'get':
    case 'delete':
      await instance[method](
        option.path,
        {
          params: option.params
        }
      )
        .then((rel: any) => {
          result = rel
        })
        .catch((err: any) => {
          result = err
        })
      break
    case 'post':
    case 'put':
      await instance[method](
        option.path,
        option.params
      )
        .then((rel: any) => {
          result = rel
        })
        .catch((err: any) => {
          result = err
        })
      break
  }
  return result ? result.data : result
}

export default http
